var Api = require("../../utils/api.js");
var util = require("../../utils/util.js");
var Auth = require("../../utils/auth.js");

var wxApi = require("../../utils/wxApi.js");
var wxRequest = require("../../utils/wxRequest.js");
var app = getApp();
var webSiteName = config.getWebsiteName;
var domain = config.getDomain;
import config from "../../utils/config.js";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        windowHeight: "100%",
        juanhao: "扫卷号",
        chanpin: "扫卷号",
        array2: ["-请选择车辆品牌-", "奥迪", "宝马", "奔驰", "丰田"],
        filterList: [],
        filterEmpty: false,
        cheliangpinpai: -1,
        cheliangpinpaiToSearch: "",
        cheliangpinpaiToSearchTip: "",
        channel_array: ["请选择","天猫", "京东", "拼多多", "新媒体", "其他"],
        array3: ["-请选择汽车类型-", "轿车", "SUV", "大型SUV", "MPV", "超跑"],
        leixing: 0, //用于算价格
        chexing: "",
        xiaohao: "",
        zhibao: 0,
        zhibaoneirong: "",
        chepaihao: "",
        chejiahao: "",
        chezhu: "",
        shoujihao: "",
        mendian: "",
        jiedai: "",
        jiage: "",
        shichangjia: "", 
        radio: 1,
        channel: 1,
        channel_type:0,
        date: "-请选择日期-",
        size1: false,
        size2: false,
        size3: false,
        size4: false,
        size5: false,
        size6: false,
        size7: false,
        size8: false,
        size9: false,
        size10: false,
        // size11:false,
        // size12:false,
        // size13:false,
        // size14:false,
        // size15:false,
        // size16:false,
        shigongtu: "",
        example_hide:false,
        // 展示的图片列表
        files: [],
        // 最多可上传的图片数量
        maxCount: {
            type: Number,
            value: 6,
        },
        // 单张图片的大小限制，单位 M
        size: {
            type: Number,
            value: 1,
        },
        // 图片大小类型。original：原图，comperssed：压缩图
        sizeType: {
            type: Array,
            value: ["original", "comperssed"],
        },
        // 图片来源类型。album：从相册选图，camera：使用相机
        sourceType: {
            type: Array,
            value: ["album", "camera"],
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //需要用户登录
        var self = this;

        wx.getSystemInfo({
            success: (result) => {
                self.setData({
                    windowHeight: result.windowHeight,
                    windowWidth: result.windowWidth,
                });
                console.log(result.inFinChat);
                if (result.inFinChat) {
                    self.setData({
                        inFinChat: result.inFinChat,
                    });
                } else {
                    Auth.setUserInfoData(self);
                    Auth.checkLogin(self);
                    self.setData({
                        copyright: getApp().globalData.copyright,
                    });
                    Auth.checkSession(self, "isLoginNow");
                }
            },
        });
        wx.request({
            url: "https://a.ygtape.com.cn/index.php/qualityassurance/index/get_brand",
            method: "POST",
            header: {
                "content-type": "application/x-www-form-urlencoded",
            },
            success: function (res) {
                // res.data.data.unshift('-请选择车辆品牌-')
                self.setData({
                    array2: res.data.data,
                    cheliangpinpaiToSearchTip: `当前共有 ${res.data.data.length} 条车辆品牌信息`
                });
            },
        });
        self.setData({
            mendian: this.data.userLevel.levelName,
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() { },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() { },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() { },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() { },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() { },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() { },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() { },

    // 滚动视图点击事件
    scroolViewClick(event) {
        let { index, name } = event.currentTarget.dataset;
        this.setData({ cheliangpinpai: index, cheliangpinpaiName: name });
    },

    // 获取输入框输入字符
    getInputVal(event) {
        let inputVal = event.detail.value, len, cheliangpinpaiToSearch = inputVal.toUpperCase(),
            cheliangpinpaiToSearchTip, filterListTemp = [], { array2 } = this.data;
        len = cheliangpinpaiToSearch.length;

        if (len == 0) {
            cheliangpinpaiToSearchTip = `当前共有 ${array2.length} 条车辆品牌信息`;
        }

        for (let i = 0; i < array2.length; i++) {
            if (array2[i].indexOf(cheliangpinpaiToSearch) != -1)
                filterListTemp.push(array2[i]);
        }

        if (filterListTemp.length == 0) {
            cheliangpinpaiToSearchTip = "输入的关键字还没有相关的车辆品牌！";
        } else if (filterListTemp.length != 0 && inputVal != "") {
            cheliangpinpaiToSearchTip = `当前过滤到 ${filterListTemp.length} 条车辆品牌信息`;
        }
        this.setData({
            cheliangpinpaiToSearch,
            cheliangpinpaiToSearchTip,
            filterList: filterListTemp,
        });
    },

    // 选定车辆品牌确定按钮
    cheliangpinpaiToSure(res) {
        const { detail } = res, { filterList, array2, cheliangpinpaiName } = this.data;
        if (detail.cancel) {
            this.setData({
                cheliangpinpai: "-1",
                cheliangpinpaiToSearch: '',
                filterList: [],
                cheliangpinpaiToSearchTip :`当前共有 ${array2.length} 条车辆品牌信息`
            })
        };
        if (detail.confirm) {
            this.setData({
                cheliangpinpai: array2.indexOf(cheliangpinpaiName),
                cheliangpinpaiToSearch: '',
                filterList: [],
                
            });
        }
    },

    // 激活车辆品牌模态窗口
    cheliangpinpaiChange() {
        this.setData({ modalType: "cheliangpinpai" });
    },

    scanCode: function () {
        var that = this;
        var self = this;
        wx.scanCode({
            scanType: ["barCode", "qrCode", "datamatrix", "pdf417", "pdf147"],
            // onlyFromCamera: true,
            success(res) {
                let result = res.result;
                that.setData({
                    juanhao: result,
                });
                wx.request({
                    url:
                        "https://a.ygtape.com.cn/index.php/qualityassurance/index/get_product_info",
                    method: "post",
                    data: {
                        reel_num: result,
                        mobile: self.data.userInfo.user_mobile,
                    },
                    success: function (res) {
                        console.log(res);
                        if (res.data.status == 200) {
                            let new_data = res.data.data;
                            let redio_type = 1;
                            switch (new_data.类型) {
                                case "漆面膜":
                                    redio_type = 1;
                                    break;
                                case "窗膜":
                                    redio_type = 2;
                                    break;
                                case "redirectTo":
                                    redio_type = 3;
                                    break;
                                default:
                                    break;
                            }
                            self.setData({
                                radio: redio_type,
                                zhibao: new_data.质保年,
                                zhibaoneirong: new_data.质保内容,
                                chanpin: new_data.产品,
                            });
                            //判断是否有变化，有变化就清除掉 分类
                            //that.getPriceOne(that.data.chanpin,that.data.leixing);
                        } else {
                        }
                    },
                });
            },
            fail: (res) => {
                //扫码失败后
                console.log(res);
                wx.showToast({
                    title: "扫码失败",
                    icon: "loading",
                    duration: 500,
                });
            },
        });
    },
    getPriceOne(chanpin, leixing) {
        let that = this;
        console.log(chanpin + "---" + leixing);
        if (chanpin && leixing) {
            wx.request({
                url: "https://a.ygtape.com.cn/index.php/film/index/getPriceOne",
                method: "post",
                data: { 
                    chanpin: chanpin, 
                    leixing: that.data.array3[leixing],
                },
                success: function (res) {
                    if (res.statusCode == 200) {
                        that.setData({
                            shichangjia: res.data.guidance_price,
                        });
                    }
                },
            });
        } else {
            that.setData({
                shichangjia: "",
            });
        }
    },
    size4Change: function (e) {
        if (e.target.dataset.index == 1) {
            //侧后挡
            this.setData({
                size2: e.detail,
                size3: e.detail,
                size4: e.detail,
                size5: e.detail,
                size6: e.detail,
                size7: e.detail,
                size8: e.detail,
                size9: e.detail,
                size10: e.detail,
            });
        } else if (e.target.dataset.index != 1 && !e.detail) {
            this.setData({
                size1: e.detail,
            });
        }
        var target = "size" + e.target.dataset.index;
        this.setData({
            [target]: e.detail,
        });
    },
    bindPickerChange: function (e) {
        this.setData({
            chanpin: e.detail.value,
        });
    },
    bindPickerType:function(e){
        let that = this;
        that.setData({
            channel_type: e.detail.value,
        });
    },
    bindPickerChangeCheXing: function (e) {
        let that = this;
        that.setData({
            leixing: e.detail.value,
        });
        //开始算 价格
        that.getPriceOne(that.data.chanpin, that.data.leixing);
    },

    bindPickerChange2: function (e) {
        this.setData({
            cheliangpinpai: e.detail.value,
        });
    },
    bindPickerChange3: function (e) {
        this.setData({
            chexing: e.detail.value,
        });
    },
    bindPickerChange5: function (e) {
        this.setData({
            jiedai: e.detail.value,
        });
    },
    uploadImage: function (e) {
        var that = this;
        wx.chooseMedia({
            count: 9,
            mediaType: ["image"],
            sourceType: ["camera"],
            camera: "back",
            // sizeType:['compressed'],  // 选择压缩图
            success(res) {
                // wx.uploadFile({
                //   url:'https://example.weixin.qq.com/upload', //仅为示例，非真实的接口地址
                //   filePath: that.data.img_arr[i],
                //   name: 'content',
                //   formData: {
                //     'user': adds
                //   },
                //   success: function (res) {
                //     console.log(res, "上传图片啦")
                //     if (res) {
                //       wx.showToast({
                //         title: '已提交发布！',
                //         duration: 3000
                //       });
                //     }
                //   }
                // })

                that.setData({
                    shigongtu: res.tempFiles[0].tempFilePath,
                });
                // console.log(res.tempFiles[0].tempFilePath)
                // console.log(res.tempFiles[0].size)
            },
        });
    },
    tips_msg(msg, time = 1000, icon = "none") {
        wx.showToast({
            icon: icon,
            title: msg,
            duration: time,
        });
    },
    tijiao: function (e) {
        //验证是否信息填写完毕
        var data = this.data;

        data.add_user_phone = this.data.userInfo.user_mobile;
        data.add_user = this.data.userInfo.nickName;
        if (!data.chanpin || data.chanpin == "扫卷号") {
            this.tips_msg("产品为必填，请扫正确的标识卡条形码！");
            return;
        }
        if (!data.juanhao || data.juanhao == "扫卷号") {
            this.tips_msg("卷号为必填，请扫正确的标识卡条形码！");
            return;
        }
        if (!data.xiaohao) {
            this.tips_msg("消耗米为必填！", 1500, "error");
            return;
        }

        if (data.cheliangpinpai == "0") {
            this.tips_msg("请选择车品牌！", 1500, "error");
            return;
        }
        if (data.leixing == "0") {
            this.tips_msg("请选择汽车类型", 1500, "error");
            return;
        }

        // if (!data.chepaihao) {
        //     this.tips_msg('车牌号为必填！', 1500, 'error');
        //     return
        // }
        if (!data.chejiahao) {
            this.tips_msg("车架号为必填！", 1500, "error");
            return;
        }
        if (data.date == "-请选择日期-") {
            this.tips_msg("请选择装贴日期", 1500, "error");
            return;
        }
        //附件必须四张图
        if (data.files.length < 4) {
            this.tips_msg("装贴施工图必须大于4张！");
            return;
        }
        data.channel_value = data.channel_array[data.channel_type];
    
        (data.token = this.data.userInfo.token),
            wx.request({
                url: "https://a.ygtape.com.cn/index.php/qualityassurance/index/add",
                method: "POST",
                data: data,
                header: {
                    "content-type": "application/x-www-form-urlencoded",
                },
                success: function (res) {
                    console.log(res.data.status);
                    if (res.data.status == 200) {
                        wx.showToast({
                            title: "新增成功",
                            duration: 2000,
                        });
                        setTimeout(function () {
                            wx.navigateTo({
                                url:
                                    "../warrantyManageList/manageList?mobile=" +
                                    data.mobile +
                                    "&token=" +
                                    data.token,
                            });
                        }, 1000);
                    } else {
                        wx.showToast({
                            title: "操作失败，请检查字段是否有错误",
                            duration: 2000,
                            icon: 'error',
                        });
                    }
                },
            });
    },
    image_example:function(e){
        //example_hide
        let that = this;
        that.setData({
            example_hide: true
        });
        //打开 弹出框    
        console.log('打开范例');
    },
    handleChooseImage: function (e) {
        var that = this;

        // 选择图片
        wx.chooseMedia({
            count: 6,
            mediaType: ["image"],
            sourceType: ["album", "camera"],
            camera: "back",
            sizeType:['compressed'],  // 选择压缩图 
            success(res) {
                console.log('success');
                console.log(res);    //选择成功的文件地址
                res.tempFiles.forEach((element) => {
                    // if(element.size >= 5242880){
                    //     wx.showToast({
                    //         title: "请上传小于5mb的图片",
                    //         duration: 2000,
                    //         icon: 'error',
                    //     });
                    //     return
                    // }
                    wx.uploadFile({
                        url: "https://a.ygtape.com.cn/index.php/qualityassurance/index/upload", //仅为示例，非真实的接口地址
                        filePath: element.tempFilePath,
                        name: "file",
                        formData: {
                            mobile: that.data.userInfo.user_mobile,
                            token: that.data.userInfo.token,
                        },
                        success: function (res) {
                            res.data = JSON.parse(res.data);
                            if (res.data.status == 200) {
                                that.setData({
                                    files: [...that.data.files, res.data.url],
                                });
                            } else {
                                wx.showToast({
                                    title: "上传失败",
                                    icon: "error",
                                    duration: 1000,
                                });
                            }
                        },
                    });
                });
                // console.log(that.data.files)
                // that.setData({
                //   files: [...that.data.files, res.tempFiles[0].tempFilePath]
                // })
                // console.log(res.tempFiles[0].tempFilePath)
                // console.log(res.tempFiles.size)
            },
            fail(res) {
                console.log('error');
                console.log(res);
            }
        });
    },

    // 预览图片
    handlePreviewImage: function (e) {
        const { index } = e.currentTarget.dataset;
        const { files } = this.data;
        wx.previewImage({
            urls: files,
            current: files[index],
        });
    },

    // 删除图片
    handleDeleteImage: function (e) {
        const { index } = e.currentTarget.dataset;
        let files = [...this.data.files];
        files.splice(index, 1);
        this.setData({
            files,
        });
    },

    radioChange: function (e) {
        //切换下面的 块和复制
        this.setData({
            radio: e.detail,
        });
    },
    channelRadioChange: function (e) {
        //切换下面的 块和复制
        this.setData({
            channel: e.detail,
        });
    },
    bindDateChange: function (e) {
        this.setData({
            date: e.detail.value,
        });
    },
    getinputVlue: function (e) {
        var self = this;
        var name = e.currentTarget.dataset.name;
        self.setData({
            [name]: e.detail.value,
        });
    },
});
